import property from './nested-property.js';
import { keyBy } from 'lodash';
function createTree(array, rootNodes, customId, childrenKey) {
  var tree = [];

  for (var rootNode in rootNodes) {
    var node = rootNodes[rootNode];
    var childNode = array[node[customId]];

    if (!node && !rootNodes.hasOwnProperty(rootNode)) {
      continue;
    }

    if (childNode) {
      node[childrenKey] = createTree(array, childNode, customId, childrenKey);
    }

    tree.push(node);
  }

  return tree;
}

function groupByParents(array, options) {
  var arrayByID = keyBy(array, options.customId);

  return array.reduce(function (prev, item) {
    var parentID = property.get(item, options.parentKey);
    if (!parentID || !arrayByID.hasOwnProperty(parentID)) {
      parentID = options.rootId;
    }

    if (parentID && prev.hasOwnProperty(parentID)) {
      prev[parentID].push(item);
      return prev;
    }

    prev[parentID] = [item];
    return prev;
  }, {});
}

function isObject(o) {
  return Object.prototype.toString.call(o) === '[object Object]';
}

function deepClone(data) {
  if (Array.isArray(data)) {
    return data.map(deepClone);
  } else if (isObject(data)) {
    return Object.keys(data).reduce(function (o, k) {
      o[k] = deepClone(data[k]);
      return o;
    }, {});
  } else {
    return data;
  }
}

/* 
parentKey: 可在其中找到指向父节点的链接的属性的名称。默认值：'parentId'。
childrenKey: 将要存储子节点的属性的名称。默认值： 'children'
customId: 唯一节点标识符。默认值： 'id'。
*/
export default function (data, options) {
  options = Object.assign(
    {
      parentKey: 'parentId',
      childrenKey: 'children',
      customId: 'id',
      rootId: '0',
    },
    options,
  );

  if (!Array.isArray(data)) {
    throw new TypeError('Expected an array but got an invalid argument');
  }

  var grouped = groupByParents(deepClone(data), options);
  return createTree(
    grouped,
    grouped[options.rootId],
    options.customId,
    options.childrenKey,
  );
}
